package com.UnionPayCenter.service.serviceImpl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.UnionPayCenter.entity.ManagerEntity;
import com.UnionPayCenter.entity.OperationInfos;
import com.UnionPayCenter.entity.OperationScenes;
import com.UnionPayCenter.enums.ErrorCodeEnum;
import com.UnionPayCenter.exception.ApiException;
import com.UnionPayCenter.mapper.ManagerMapper;
import com.UnionPayCenter.mapper.OperationScenesMapper;
import com.UnionPayCenter.service.IOperationScenesService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
@Transactional
public class OperationScenesServiceImpl implements IOperationScenesService{
    @Autowired
    private ManagerMapper managerMapper;
    @Autowired
    private OperationScenesMapper operScenesMapper;

    @Override
    public PageInfo<OperationScenes> findList(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            // 页数
            Integer page = jsonParam.getInteger("page");
            if (page == null) {
                page = 1;
            }
            // 每页条数
            Integer pageSize = jsonParam.getInteger("pageSize");
            if (pageSize == null) {
                pageSize = 20;
            }
            PageHelper.startPage(page, pageSize);

            Integer type = jsonParam.getInteger("type");
            List<OperationScenes> list = operScenesMapper.selectList(shopId, type);
            PageInfo<OperationScenes> pageList = new PageInfo<>(list);
            return pageList;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    @Override
    public boolean add(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            String opsName = jsonParam.getString("opsName");
            Integer type = jsonParam.getInteger("type");
            Integer amount = jsonParam.getInteger("amount");
            JSONArray couponList = jsonParam.getJSONArray("couponList");
            
            OperationScenes opsEntity = operScenesMapper.selectByName(opsName, shopId);
            if (opsEntity != null) {
                throw new ApiException(ErrorCodeEnum.FL500.code(), String.format(ErrorCodeEnum.FL500.msg().concat("[%s]"), "场景名称已存在"));
            }
            
            //一家商铺只能创建一个注册成功后赠送优惠券的场景
            OperationScenes regScenes = operScenesMapper.selectRegType(shopId);
            if (type == 1 && regScenes != null) {
                throw new ApiException(ErrorCodeEnum.FL500.code(), String.format(ErrorCodeEnum.FL500.msg().concat("[%s]"), "注册送场景已存在"));
            }
            
            opsEntity = new OperationScenes();
            opsEntity.setShopId(shopId);
            opsEntity.setOpsName(opsName);
            opsEntity.setType(type);
            opsEntity.setAmount(amount);
            operScenesMapper.insertSelective(opsEntity);
            
            this.insertOperationInfo(opsEntity.getOpsId(), couponList);
            
            return true;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    /**
     * 保存运营场景优惠券信息
     * @param opsId
     * @param couponList
     */
    private void insertOperationInfo(Integer opsId, JSONArray couponList) {
        List<OperationInfos> operInfoList = new ArrayList<>();
        OperationInfos operSet;
        if (couponList != null && couponList.size() > 0) {
            for(int i=0; i < couponList.size(); i++) {
                JSONObject json = JSONObject.parseObject(couponList.getString(i));
                Integer disTypeId = json.getInteger("disTypeId");
                Integer count = json.getInteger("count");
                
                operSet = new OperationInfos();
                operSet.setOpsId(opsId);
                operSet.setDisTypeId(disTypeId);
                operSet.setCount(count);

                operInfoList.add(operSet);
            }
            
            //删除原来的设置
            operScenesMapper.deleteOldInfo(opsId);
            if (operInfoList.size() > 0) {
                //插入新设置
                operScenesMapper.insertInfoList(operInfoList);
            }
        } else {
            throw new ApiException(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "couponList"));
        }
        
    }

    @Override
    public boolean update(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            Integer opsId = jsonParam.getInteger("opsId");
            String opsName = jsonParam.getString("opsName");
            Integer type = jsonParam.getInteger("type");
            Integer amount = jsonParam.getInteger("amount");
            JSONArray couponList = jsonParam.getJSONArray("couponList");
            
            OperationScenes exists = operScenesMapper.selectByPrimaryKey(opsId);
            if (exists == null) {
                throw new ApiException(ErrorCodeEnum.FL500.code(), String.format(ErrorCodeEnum.FL500.msg().concat("[%s]"), "opsId不存在"));
            }
            
            //一家商铺只能创建一个注册成功后赠送优惠券的场景
            OperationScenes regScenes = operScenesMapper.selectRegType(shopId);
            if (type == 1 && regScenes != null && regScenes.getOpsId() != opsId) {
                throw new ApiException(ErrorCodeEnum.FL500.code(), String.format(ErrorCodeEnum.FL500.msg().concat("[%s]"), "注册送场景已存在"));
            }
            
            OperationScenes opsEntity = new OperationScenes();
            opsEntity.setOpsId(opsId);
            opsEntity.setOpsName(opsName);
            opsEntity.setType(type);
            opsEntity.setAmount(amount);
            operScenesMapper.updateByPrimaryKeySelective(opsEntity);
            
            this.insertOperationInfo(opsId, couponList);
            
            return true;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    @Override
    public boolean updateStatus(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            Integer opsId = jsonParam.getInteger("opsId");
            Integer status = jsonParam.getInteger("status");
            
            OperationScenes opsEntity = new OperationScenes();
            opsEntity.setOpsId(opsId);
            opsEntity.setStatus(status);
            operScenesMapper.updateByPrimaryKeySelective(opsEntity);
            
            return true;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    @Override
    public Map<String, Object> findOperInfo(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            Map<String, Object> resultMap = new HashMap<String, Object>();
            
            Integer opsId = jsonParam.getInteger("opsId");
            OperationScenes opsEntity = operScenesMapper.selectByPrimaryKey(opsId);
            if (opsEntity == null) {
                throw new ApiException(ErrorCodeEnum.FL500.code(), String.format(ErrorCodeEnum.FL500.msg().concat("[%s]"), "opsId不存在"));
            }
            
            List<OperationInfos> infoList = operScenesMapper.selectOperInfoList(opsId);
            List<Map<String, Object>> list = new ArrayList<>();
            if (infoList.size() > 0) {
                for (OperationInfos info : infoList) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("disTypeId", info.getDisTypeId());
                    map.put("count", info.getCount());
                    list.add(map);
                }
            }
            
            resultMap.put("opsId", opsEntity.getOpsId());
            resultMap.put("opsName", opsEntity.getOpsName());
            resultMap.put("type", opsEntity.getType());
            resultMap.put("amount", opsEntity.getAmount());
            resultMap.put("couponList", list);
            
            return resultMap;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

}
